#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import datetime
from functools import wraps
from flask import Module, Response, request, flash, jsonify, g, current_app,\
    abort, redirect, url_for, session, Blueprint, render_template

from planet.account import api
from planet.account.models import User, Profile
from planet.extensions import db, cache


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth:
            message = {
                'status_code': 10001,
                'message': 'Login required',
            }
            resp = jsonify(message)
            return resp
        else:
            user, authenticated = User.query.authenticate(auth.username,
                                                          auth.password)
            if not authenticated:
                message = {
                    'status_code': 10002,
                    'message': 'Authentication Failed',
                }
                resp = jsonify(message)
                return resp
        return f(*args, **kwargs)
    return decorated


@api.route("/account/verify_credentials", methods=['GET'])
@requires_auth
def verify_credentials():
    # print request.headers
    account = request.authorization.username
    user = User.query.filter(db.or_(User.username == account,
                                    User.email == account)).first()
    if not user.profile:
        profile = Profile()
        user.profile = profile

        db.session.add(user)
        db.session.commit()

    message = {
        'status_code': 10000,
        'message': 'success',
        'user': {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'phone': user.profile.phone or '',
        }
    }
    resp = jsonify(message)
    resp.mimetype = 'application/json'
    return resp


@api.route("/account/create", methods=['POST'])
def create():
    if request.authorization:
        message = {
            'status_code': 10003,
            'message': 'You have authentication',
        }
        resp = jsonify(message)
        return resp

    email = request.values.get('email')
    username = request.values.get('username')
    password = request.values.get('password')
    password_confirm = request.values.get('password_confirm')

    if not email or not username or not password or not password_confirm:
        message = {
            'status_code': 20001,
            'message': 'args is null',
        }
        resp = jsonify(message)
        return resp

    if password != password_confirm:
        message = {
            'status_code': 20002,
            'message': 'password does not matchrd'
        }
        resp = jsonify(message)
        return resp

    user = User.query.filter_by(email=email).first()
    if user:
        message = {
            'status_code': 20003,
            'message': 'email exists'
        }
        resp = jsonify(message)
        return resp

    user = User.query.filter_by(username=username).first()
    if user:
        message = {
            'status_code': 20004,
            'message': 'username exists'
        }
        resp = jsonify(message)
        return resp

    new_user = User(email=email, username=username, nickname=username,
                    password=password)
    profile = Profile()
    new_user.profile = profile
    db.session.add(new_user)
    db.session.commit()
    message = {
        'status_code': 10000,
        'message': 'success',
        'user': {
            'id': new_user.id,
            'username': new_user.username,
            'email': new_user.email,
        }
    }
    resp = jsonify(message)
    resp.mimetype = 'application/json'
    return resp


@api.route("/account/password_update", methods=['POST'])
@requires_auth
def password_update():
    current_password = request.values.get('current_password')
    new_password = request.values.get('new_password')
    repeat_password = request.values.get('repeat_password')

    if not current_password or not new_password or not repeat_password:
        message = {
            'status_code': 20001,
            'message': 'args is null',
        }
        resp = jsonify(message)
        resp.mimetype = 'application/json'
        return resp

    if new_password != repeat_password:
        message = {
            'status_code': 20002,
            'message': 'password does not matchrd'
        }
        resp = jsonify(message)
        resp.mimetype = 'application/json'
        return resp

    auth = request.authorization
    user, authenticated = User.query.authenticate(auth.username,
                                                  current_password)
    if not authenticated:
        message = {
            'status_code': 10002,
            'message': 'the password is wrong',
        }
        resp = jsonify(message)
        resp.mimetype = 'application/json'
        return resp

    user.password = new_password
    db.session.add(user)
    db.session.commit()
    message = {
        'status_code': 10000,
        'message': 'success',
    }
    resp = jsonify(message)
    resp.mimetype = 'application/json'
    return resp


@api.route("/account/contact_update", methods=['POST'])
@requires_auth
def contact_update():
    phone = request.values.get('phone')
    auth = request.authorization
    user = User.query.filter_by(username=auth.username).first()
    profile = user.profile
    if not profile:
        profile = Profile()
        profile.user = user

    profile.phone = phone
    db.session.add(user)
    db.session.commit()
    message = {
        'status_code': 10000,
        'message': 'success',
    }
    resp = jsonify(message)
    resp.mimetype = 'application/json'
    return resp
